﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using cnFederal.FaCode;

namespace cnFederal
{
      
    public partial class EditSelectedLink : System.Web.UI.Page
    {
        CnfiLink _link;
        CultureInfo _ci;
        string _imageUrl;

        public EditSelectedLink()
        {
            _ci = new CultureInfo("nb-NO");
            CnfiLinks.Load();
            CnfImages.Load();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int id = -1;
           
            string query = Request.QueryString["Id"];
            if (string.IsNullOrWhiteSpace(query))
                txtRegDate.Text = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;

            if (!string.IsNullOrWhiteSpace(query))
            {

                try
                {
                    id = int.Parse(query);
                }
                catch (Exception ex) { }
                if (id != -1)
                    Load(id);

            }
            if (Session["ImageUrl"] != null)
                this._imageUrl = Session["ImageUrl"].ToString();
            MainTable.Visible = UserIdentity.Autenticated;
        }

        public string ImageUrl
        {
            get { return _imageUrl; }
            set { _imageUrl = value; }
        }

        public void Load(int id)
        {
            _link = CnfiLinks.GetFaLinkById(id);
            if (!IsPostBack && _link != null)
            {
                txtRegDate.Text = _link.DateRegistered.Year + "-" + _link.DateRegistered.Month + "-" + _link.DateRegistered.Day;
                txtTitle.Text = _link.Title;
                
                txtDescription.Text = _link.Description;
                TxtUrl.Text = _link.LinkUrl;
               
                imageSelected.ImageUrl = _link.ImageUrl;
            }
        }

        protected void txtRegDate_TextChanged(object sender, EventArgs e)
        {



        }

        private void CheckHttp()
        {
            if (!this.TxtUrl.Text.Contains(@"http://"))
            {
                string uri = @"http://" + this.TxtUrl.Text;
                this.TxtUrl.Text = uri;

            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int itemId = 0;
            CheckHttp();
            if (_link == null)
               itemId =  CreateNew();
            else
                Update();

            string id = Request.QueryString["Id"];
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (itemId == 0)
                    itemId = Convert.ToInt32(id);
                if (_image != null)
                {
                    _image.LinkId = itemId;
                    _image.LinkType = (int)SysObjects.LINK;
                    CnfImages.Save(_image);
                }
            }
            string query = @"~/Admin/EditSelectedLink.aspx";
            Response.Redirect(query);
        }


        private void Update()
        {
            _link.Description = txtDescription.Text;
            _link.LinkUrl = TxtUrl.Text;
            if (!string.IsNullOrWhiteSpace(this.ImageUrl))
                _link.ImageUrl = this.ImageUrl;
            _link.Title = txtTitle.Text;
           
            CnfiLinks.Save(_link);
        }

        private int CreateNew()
        {
            _link = new CnfiLink();
            _link.EkxternalTableId = 0; //not used in this context.
            _link.PostId = 0;
            _link.DateRegistered = DateTime.Now;
            _link.Description = txtDescription.Text;
            _link.LinkUrl = TxtUrl.Text;
            _link.ImageUrl = this.ImageUrl;
            _link.Title = txtTitle.Text;
           return CnfiLinks.CreateNew(_link);
        }


        protected void btnBrows_Click(object sender, EventArgs e)
        {
            UploadImage();
            //Response.Redirect(Request.RawUrl);

        }

    

        public string RootDomain
        {
            get
            {
                return HttpContext.Current.Request.Url.Authority;
            }
        }
        public string AbsoluteURI
        {
            get
            {
                return HttpContext.Current.Request.Url.AbsoluteUri;
            }
        }

        CnfImage _image;
        private void UploadImage()
        {
            string msg = "";
            if (fileupload1.HasFile)
            {
                try
                {
                    string[] sTypes = { "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", "image/x-png", "image/png" };
                    bool bIsMatch = false;
                    foreach (string sType in sTypes)
                    {
                        if (String.Compare(sType, fileupload1.PostedFile.ContentType, true) == 0)
                            bIsMatch = true;
                    }

                    if (bIsMatch)
                    {
                        if (fileupload1.PostedFile.ContentLength < 1002400)
                        {
                            // string appPath = Request.PhysicalApplicationPath;

                            string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
                            //fileupload1.SaveAs(Server.MapPath(Path.Combine("~/Images/", filename)));
                            _image = CnfImages.GetImageByName(fileupload1.FileName);
                            if (_image == null)
                            {
                                CnfImage img = new CnfImage();
                                img.Image = fileupload1.FileBytes;
                                img.ImageName = fileupload1.FileName;
                                if (_link != null)
                                    img.LinkId = _link.Id;
                                img.LinkType = (int)SysObjects.LINK;
                                CnfImages.CreateNew(img);
                                _image = CnfImages.GetLastAddedImage();

                            }
                            this._imageUrl = "http://"+RootDomain +"/ImgHandler.ashx?id=" + _image.Id;
                            Session["ImageUrl"] = this._imageUrl;
                            this.imageSelected.ImageUrl = this._imageUrl;

                        }
                        else
                            msg = "Upload status: The file has to be less than 1 MB!";
                    }
                    else
                        msg = "Upload status: Only JPEG files are accepted!";
                }
                catch (Exception ex)
                {
                    msg = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }

        }












    }
}